package com.v1.video.activity;

import java.util.ArrayList;

import org.apache.http.impl.client.EntityEnclosingRequestWrapper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.Surface;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.utovr.player.UVEventListener;
import com.utovr.player.UVInfoListener;
import com.utovr.player.UVMediaPlayer;
import com.utovr.player.UVMediaType;
import com.utovr.player.UVPlayerCallBack;
import com.utovr.player.UVReaderType;
import com.v1.video.R;
import com.v1.video.domain.VideoFileEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

/**
 * Copyright @2015 上海杰图软件技术有限公司
 * 
 * 运行环境需求：Android 4.1（API level 16）及其以上版本 UtoVR全景播放集成 1.必要的res
 * SDK所需的资源文件，请查看UtoVRSDK\lib\res目录。包括values\ids.xml、anim\loading.xml、以及loading所
 * 需图片（drawable-hdpi和drawable-xhdpi两个目录下），开发者可以修改资源内容（anim\loading.xml的内容、
 * drawable-hdpi和drawable-xhdpi两个目录下图片）但不可改变资源名称（values\ids.xml的文件名以及里面的
 * load_icon、anim\loading.xml的文件名），如果开发者重新建立工程或将UtoVR播放器集成到自己工程，请将该目
 * 录下所有文件拷贝到工程对应目录下。 2.libs
 * SDK的库文件（so和jar文件），请查看UtoVRSDK\lib\libs目录。将libs下所有文件拷贝到工程libs下对应目录 tips:
 * .so文件导入，在build文件中添加处理，请参照UtoVRPlayerDemo对应处理：build文件中 task
 * nativeLibsToJar以及tasks.withType(JavaCompile) 3.权限
 * android.permission.WAKE_LOCK android.permission.WRITE_EXTERNAL_STORAGE
 * android.permission.READ_EXTERNAL_STORAGE android.permission.INTERNET
 * 4.opengl版本 在AndroidManifest.xml中添加： uses-feature
 * android:glEsVersion="0x00020000" android:required="true" 5.混淆 -dontwarn
 * com.google.** -dontwarn android.media.** -keepattributes InnerClasses,
 * Signature, *Annotation* -keep class com.utovr.** {*;} -keep class
 * com.google.** {*;} -keep class android.media.** {*;
 * 
 * 注意： 设置播放路径setSource(UVMediaType type, String path)时，务必设置文件格式
 * 
 */
public class VideoPlayerVRActivity2 extends Activity implements
		UVPlayerCallBack {
	private final String TAG = "VideoPlayerVRActivity";

	private UVMediaPlayer mMediaplayer = null; // 媒体视频播放器
	private Handler handler = null;
	private ToggleButton playpauseBtn; // 启动、暂停按钮
	protected SeekBar time_Seekbar; // 播放进度条
	protected TextView time_TextView; // 时间长度
	private String videoTimeString = null; // 时间长度文本
	protected ToggleButton gyroBtn; // 陀螺仪控制按钮
	protected ToggleButton screenBtn; // 单双屏
	private PowerManager.WakeLock mWakeLock = null;
	private boolean bufferResume = true;
	private boolean needBufferAnim = false;
	private ImageView imgBuffer; // 缓冲动画
	// private String Path = "/sdcard/wu.mp4"; // setSource
	// UVMediaType.UVMEDIA_TYPE_MP4
	// private String videoUrl =
	// "http://cache.utovr.com/201508270528174780.m3u8"; //setSource
	// UVMediaType.UVMEDIA_TYPE_M3U8
	private String mVid = "";

	private ArrayList<String> mVidlst = new ArrayList<String>();
	private int pos = -1;
	private boolean isPlayList = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_video_vr);
		handler = new Handler();
		PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
		mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
				"mytag");
		mWakeLock.acquire();
		initView();
		initData();

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mMediaplayer != null) {
			mMediaplayer.onResume(this);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mMediaplayer != null) {
			mMediaplayer.onPause();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mWakeLock.release();
		if (mMediaplayer != null) {
			mMediaplayer.release();
		}
	}

	/**
	 * SDK已经将播放器环境已设置好，可以播放了
	 */
	@Override
	public void createEnv(final Surface surface) {
		if (mMediaplayer != null && mMediaplayer.isInited()) {
			mMediaplayer.setSurface(surface);
		}
		handler.post(new Runnable() {
			@Override
			public void run() {
				try {
					// 创建媒体视频播放器
					mMediaplayer.initPlayer();
					mMediaplayer.setListener(mListener);
					mMediaplayer.setSurface(surface);
					mMediaplayer.setInfoListener(mInfoListener);
					try {
						/******************** 播放网络m3u8 *******************/
						// mMediaplayer.setSource(UVMediaType.UVMEDIA_TYPE_M3U8,
						// videoUrl);
						if (isPlayList) {
							if (pos >= 0 && pos < mVidlst.size()) {
								mVid = mVidlst.get(pos);
							}
						}
						new NetEngine().getVideoFile(
								VideoPlayerVRActivity2.this, mVid,
								new OnResponseListener() {

									@Override
									public void onSuccess(Object object,
											int code, String message,
											String keyId) {
										// TODO Auto-generated method stub
										if (object != null) {
											VideoFileEntity entity = (VideoFileEntity) object;
											if (entity.getBody() != null
													&& entity.getBody()
															.getData() != null
													&& entity.getBody()
															.getData()
															.getVideofile() != null
													&& entity.getBody()
															.getData()
															.getVideofile()
															.getInfos() != null
													&& entity.getBody()
															.getData()
															.getVideofile()
															.getInfos()
															.getMp4() != null
													&& !TextUtils
															.isEmpty(entity
																	.getBody()
																	.getData()
																	.getVideofile()
																	.getInfos()
																	.getMp4()
																	.getMainUrl())) {
												Logger.i(
														TAG,
														"Mediaplayer path="
																+ entity.getBody()
																		.getData()
																		.getVideofile()
																		.getInfos()
																		.getMp4()
																		.getMainUrl());
												mMediaplayer
														.setSource(
																UVMediaType.UVMEDIA_TYPE_MP4,
																entity.getBody()
																		.getData()
																		.getVideofile()
																		.getInfos()
																		.getMp4()
																		.getMainUrl());
												needBufferAnim = true;
												/******************** 本地MP4 *******************/
											}

										} else {
											toast("鉴权失败");
										}
									}

									@Override
									public void onFailure(int code,
											String message) {
										// TODO Auto-generated method stub
										toast("获取网络地址失败");
									}
								});

						/*
						 * File file = new File(Path); if (file.exists()) {
						 * mMediaplayer.setSource(UVMediaType.UVMEDIA_TYPE_MP4,
						 * Path); } else { toast("文件不存在"); }
						 */
					} catch (IllegalStateException t) {
						Logger.e("utovr", "media setSource failed");
						t.printStackTrace();
					}
				} catch (Exception e) {
					Logger.i("utovr", e.getMessage());
				}
			}
		});
	}

	/**
	 * @param CurPostion
	 *            播放进度
	 */
	@Override
	public void updateProgress(long CurPostion) {
		Message msg = handleProgress.obtainMessage(0, (int) CurPostion, 0);
		handleProgress.sendMessage(msg);
	}

	private UVEventListener mListener = new UVEventListener() {
		@Override
		public void onRenderTypeChanged(UVReaderType arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onGyroCtrl(int arg0, String arg1) {
			// TODO Auto-generated method stub
			switch (arg0) {
			case UVEventListener.GYRO_CTRL_PLAY:
				playpauseBtn.setChecked(false);
				break;
			case UVEventListener.GYRO_CTRL_PAUSE:
				playpauseBtn.setChecked(true);
				break;
			}
		}

		@Override
		public void onStateChanged(int playbackState) {
			Logger.i("utovr", "+++++++ playbackState:" + playbackState);
			switch (playbackState) {
			case UVMediaPlayer.STATE_PREPARING:
				break;
			case UVMediaPlayer.STATE_BUFFERING:
				if (needBufferAnim && mMediaplayer != null
						&& mMediaplayer.isPlaying()) {
					bufferResume = true;
					setBufferVisibility(true);
				}
				break;
			case UVMediaPlayer.STATE_READY:
				// 设置时间和进度条
				setInfo();

				if (bufferResume) {
					bufferResume = false;
					setBufferVisibility(false);
				}
				break;
			case UVMediaPlayer.STATE_ENDED:
				// 这里是循环播放，可根据需求更改
				mMediaplayer.seekTo(0);
				if (isPlayList) {
					pos++;
					if (pos >= mVidlst.size()) {
						pos = 0;
					}
					Logger.i(TAG,
							"pos==" + pos + "lsitUrl.size==" + mVidlst.size());
					mVid = mVidlst.get(pos);
					new NetEngine().getVideoFile(VideoPlayerVRActivity2.this,
							mVid, new OnResponseListener() {

								@Override
								public void onSuccess(Object object, int code,
										String message, String keyId) {
									// TODO Auto-generated method stub
									if (object != null) {
										VideoFileEntity entity = (VideoFileEntity) object;
										if (entity.getBody() != null
												&& entity.getBody().getData() != null
												&& entity.getBody().getData()
														.getVideofile() != null
												&& entity.getBody().getData()
														.getVideofile()
														.getInfos() != null
												&& entity.getBody().getData()
														.getVideofile()
														.getInfos().getMp4() != null
												&& !TextUtils.isEmpty(entity
														.getBody().getData()
														.getVideofile()
														.getInfos().getMp4()
														.getMainUrl())) {
											mMediaplayer
													.setSource(
															UVMediaType.UVMEDIA_TYPE_MP4,
															entity.getBody()
																	.getData()
																	.getVideofile()
																	.getInfos()
																	.getMp4()
																	.getMainUrl());
										}

									} else {
										toast("鉴权失败");
									}
								}

								@Override
								public void onFailure(int code, String message) {
									// TODO Auto-generated method stub
									toast("获取网络地址失败");
								}
							});

				}
				break;
			case UVMediaPlayer.TRACK_DISABLED:
			case UVMediaPlayer.TRACK_DEFAULT:
				break;
			}
		}

		@Override
		public void onError(Exception e, int ErrType) {
			switch (ErrType) {
			case UVEventListener.ERR_TIMEOUT:
				toast("网络超时");
				break;
			case UVEventListener.ERR_INIT:
			case UVEventListener.ERR_RENDER_INIT:
			case UVEventListener.ERR_DECODE:
				toast("检查代码setSource参数UVMediaType是否正确或不支持该视频格式");
				break;
			case UVEventListener.ERR_WRITE:
				toast("WriteError");
				break;
			case UVEventListener.ERR_LOAD:
				toast("获得数据失败");
				break;
			default:
				toast("onError");
				break;
			}
		}

		@Override
		public void onVideoSizeChanged(int width, int height) {
		}
	};

	private UVInfoListener mInfoListener = new UVInfoListener() {
		@Override
		public void onBandwidthSample(int elapsedMs, long bytes,
				long bitrateEstimate) {
		}

		@Override
		public void onLoadStarted() {
		}

		@Override
		public void onLoadCompleted() {
			if (bufferResume) {
				bufferResume = false;
				setBufferVisibility(false);
			}
			/*
			 * 缓冲进度 这里比较偷懒的做法是利用m3u8分片原理更新进度，网络播放MP4这种做法肯定是不对的 你完全可以创建一个定时器调用
			 * mMediaplayer.getBufferedPosition()
			 */
			time_Seekbar.setSecondaryProgress((int) mMediaplayer
					.getBufferedPosition());

		}
	};

	private void initData() {
		Intent intent = getIntent();
		pos = intent.getIntExtra("pos", -1);
		if (pos > -1) {
			isPlayList = true;
			mVidlst = intent.getStringArrayListExtra("vid");
		} else {
			isPlayList = false;
			mVid = intent.getStringExtra("vid");
		}
		// videoUrl = "http://f02.v1.cn/transcode/14203665MOBILET2.mp4";
		Logger.i(TAG, "vid==" + mVid);
		// 初始化播放器
		RelativeLayout rlPlayView = (RelativeLayout) findViewById(R.id.video_rlPlayView);
		mMediaplayer = new UVMediaPlayer(VideoPlayerVRActivity2.this,
				rlPlayView);
		// 将工具条的显示或隐藏交个SDK管理，也可自己管理
		RelativeLayout rlToolbar = (RelativeLayout) findViewById(R.id.video_rlToolbar);
		mMediaplayer.setToolbar(rlToolbar, null, null);
	}

	private void initView() {
		// 工具栏上的按钮
		gyroBtn = (ToggleButton) findViewById(R.id.video_toolbar_btn_gyro);// 陀螺仪
		screenBtn = (ToggleButton) findViewById(R.id.video_toolbar_btn_screen);// 单双屏
		playpauseBtn = (ToggleButton) findViewById(R.id.video_toolbar_btn_playpause);// 播放/暂停
		time_Seekbar = (SeekBar) findViewById(R.id.video_toolbar_time_seekbar);// 进度
		// 陀螺仪按钮事件
		gyroBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mMediaplayer != null) {
					mMediaplayer.setGyroEnabled(!mMediaplayer.isGyroEnabled());
					gyroBtn.setChecked(mMediaplayer.isGyroEnabled());
				}
			}
		});
		// 单双屏按钮事件
		screenBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mMediaplayer != null) {
					boolean isScreen = !mMediaplayer.isDualScreenEnabled();
					mMediaplayer.setDualScreenEnabled(isScreen);
					if (isScreen) {
						mMediaplayer.setGyroEnabled(true);
						gyroBtn.setChecked(true);
						gyroBtn.setEnabled(false);
					} else {
						mMediaplayer.setGyroEnabled(false);
						gyroBtn.setChecked(false);
						gyroBtn.setEnabled(true);
					}
				}
			}
		});
		// 播放/暂停按钮事件
		playpauseBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (((ToggleButton) v).isChecked()) {
					if (mMediaplayer != null && mMediaplayer.isInited()) {// 暂停媒体视频
						mMediaplayer.pause();
					}
				} else {
					if (mMediaplayer != null && mMediaplayer.isInited()) {// 播放媒体视频
						mMediaplayer.play();
					}
				}
			}
		});
		// 进度条事件
		time_Seekbar
				.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						if (mMediaplayer != null && mMediaplayer.isInited()) {
							mMediaplayer.seekTo(seekBar.getProgress());
						}
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
					}

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
					}
				});
		imgBuffer = (ImageView) findViewById(R.id.video_imgBuffer);
		time_TextView = (TextView) findViewById(R.id.video_toolbar_time_tv);// 时间
	}

	/**
	 * 设置时间和进度条初始信息
	 */
	public void setInfo() {
		int duration = 0;
		if (mMediaplayer != null) {
			duration = (int) mMediaplayer.getDuration();
		}
		if (duration == time_Seekbar.getMax()) {
			return;
		}
		// 设置控制条,放在加载完成以后设置，防止获取getDuration()错误
		time_Seekbar.setProgress(0);
		time_Seekbar.setMax(duration);
		videoTimeString = Utils.getShowTime(duration);
		time_TextView.setText("00:00:00/" + videoTimeString);
	}

	private void toast(final String msg) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(VideoPlayerVRActivity2.this, msg,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	// 缓冲动画控制
	private void setBufferVisibility(boolean Visible) {
		if (Visible) {
			imgBuffer.setVisibility(View.VISIBLE);
			Utils.startImageAnim(imgBuffer, R.anim.play_buffer_anim);
		} else {
			Utils.stopImageAnim(imgBuffer);
			imgBuffer.setVisibility(View.GONE);
		}
	}

	/*******************************************************
	 * 通过Handler来更新进度条
	 ******************************************************/
	public Handler handleProgress = new Handler() {
		public void handleMessage(Message msg) {
			int position = msg.arg1;
			if (position >= 0 && videoTimeString != null) {
				time_Seekbar.setProgress(position);
				// 设置播放时间
				String cur = Utils.getShowTime(position);
				time_TextView.setText(cur + "/" + videoTimeString);
			}

		};
	};

}
